﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;

namespace hrainwebbase.ashx
{
    /// <summary>
    /// GetPhotoHandler 的摘要说明
    /// </summary>
    public class GetPhotoHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            try
            {
                
                string mid = context.Request.QueryString["mid"];
                string baseimg = context.Request.QueryString["baseimg"];//原图片？
                DataTable dt;
                using (HCDV.HCSP.dbsimple db = new HCDV.HCSP.dbsimple())
                {

                    dt = db.Query("select fieldinfo,savetype,fsaveurl,fsaveurlmin from sysfileinfo where fieldid='" + mid + "'");

                }
                Byte[] bts = new byte[0];
                DataRow rowinfo;
                if (dt != null && dt.Rows.Count > 0)
                {

                    rowinfo = dt.Rows[0];
                    ///uploads/20170603/20170603193442667155555.jpg
                    if (rowinfo["savetype"].ToString().Equals("dbf"))
                    {
                        bts = rowinfo[0] == DBNull.Value ? new byte[0] : (byte[])rowinfo[0];
                    }
                    else
                    {
                        var path = HttpContext.Current.Server.MapPath("~/");
                       // var file = File.Open(path + rowinfo[2].ToString(),FileMode.Open);
                        //file.Read
                        bts = File.ReadAllBytes(path + rowinfo[2].ToString());
                    }
                  
                }
                if (bts.Length == 0)
                {
                    //没有上传时使用默认图片
                    string path = "~/uploadimg/default.jpg";
                    string pyhsicalPath = System.Web.HttpContext.Current.Server.MapPath(path);
                    if (System.IO.File.Exists(pyhsicalPath))
                    {
                        FileInfo f = new FileInfo(pyhsicalPath);
                        using (FileStream fs = new FileStream(pyhsicalPath, FileMode.Open))
                        {
                            int len = (int)f.Length;
                            bts = new byte[len];
                            fs.Read(bts, 0, len);
                        }
                    }
                }
                context.Response.BinaryWrite(bts);
            }
            catch (Exception ex)
            {
            }
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}